package stack;

import java.util.Stack;

public class CalculateTest {
	public static void main(String[] args) {
		String expression = "3.1+2*6-2";

		Stack<Float> numStack = new Stack<>();
		Stack<Integer> operStack = new Stack<>();
		CalculateTest c = new CalculateTest();

		int index = 0;
		float num1 = 0;
		float num2 = 0;
		int oper = 0;
		char ch = ' ';
		float result = 0;
		String num = "";
		while (index < expression.length()) {
			ch = expression.substring(index, index + 1).charAt(0);

			if (c.isOper(ch)) {//是运算符
				if (!operStack.empty()) {//符号栈不为空，做优先级比较
					if (c.pripority(ch) <= c.pripority(operStack.peek())) {
						num1 = numStack.pop();
						num2 = numStack.pop();
						oper = operStack.pop();
						result = c.cul(num1, num2, oper);
						numStack.push(result);
						operStack.push((int) ch);
					} else {
						operStack.push((int) ch);
					}
				} else {//符号栈为空
					operStack.push((int) ch);
				}
			} else {//是数字
				num += ch;
				if (index >= expression.length() - 1 || c.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
					numStack.push(Float.parseFloat(num));
					num = "";
				}
			}
			index++;
		}
		while (!operStack.empty()) {
			num1 = numStack.pop();
			num2 = numStack.pop();
			oper = operStack.pop();
			result = c.cul(num1, num2, oper);
			numStack.push(result);
		}
		System.out.println(numStack.pop());

	}

	public boolean isOper(char ch) {
		return ch == '+' || ch == '-' || ch == '*' || ch == '/';
	}

	public int pripority(int ch) {
		if (ch == '+' || ch == '-') {
			return 0;
		} else if (ch == '*' || ch == '/') {
			return 1;
		} else {
			return -1;
		}
	}

	public float cul(float num1, float num2, int oper) {
		float reslut = 0;
		if (oper == '+') {
			reslut = num2 + num1;
		} else if (oper == '-') {
			reslut = num2 - num1;
		} else if (oper == '*') {
			reslut = num2 * num1;
		} else if (oper == '/') {
			reslut = num2 / num1;
		} else {
			throw new RuntimeException("运算出错");
		}
		return reslut;
	}
}
